package	com.sdry.web.controller.jyy.unpack;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sdry.mapper.cb.IDicMapper;
import com.sdry.model.jyy.unpack.JyyUnpacking;
import com.sdry.model.jyy.unpack.UnpackDetal;
import com.sdry.model.lz.Customer;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.jyy.unpack.JyyUnpackingService;
import com.sdry.service.jyy.unpack.UnpackDetalService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;
/**
 *
 *@ClassName: UnpackingController
 *@Description: 拆箱单Controller层
 *@Author jyy
 *@Date 2019-08-20 15:57:31
 *@version 1.0
 *
 * 修改人：吉永艳
 * 修改时间：2019-11-01
 * 修改内容，多仓库版修改，关联仓库id:216-219
 * 		    并增加log日志：49，62，87，212，224，229
 * 
 * 修改时间：2019-11-07
 * 修改内容:182-185:多仓库版修改，关联仓库id
*/
@Controller
@RequestMapping("/jyyUnpacking")
public class JyyUnpackingController{
	
	Logger logger = Logger.getLogger(JyyUnpackingController.class);  
	
	@Resource JyyUnpackingService UnpackingService;
	@Resource StockOutOrderService stockOutOrderService;
	@Resource UnpackDetalService UnpackDetalService;
	
	/**
	 * 根据id修改单子状态，班组长确认功能
	 * @param id 单子id
	 */
	@RequestMapping("/updateStatus")
	public void updateStatus(Long id, HttpServletResponse response, HttpSession httpSession) {
		
		logger.info("拆箱单据--班组长确认功能--单据id为：，"+id);
		Integer affact = 0;
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		//获取角色
		if(su != null) {
			if(su.getRoleName() != null){
				String roleName = su.getRoleName();
				
				if(roleName.contains("班长")) {
					affact = UnpackingService.updateState(id );
				}else {
					affact = -1;
				}
				
			}else {
				affact = -1;//没有角色名称
			}
		}else {
			affact = -1;//没获取到登录用户
		}
		
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			 logger.error("拆箱单据--班组长确认功能--出错--单据id为："+id);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据供应商id，在良品库查询 存在的库存信息
	 * @param
	 * @param response 良品库库存集合
	 */
	@RequestMapping("/selectAllGood")
	public void selectAllGood(JyyInfoGood jyyInfoGood, String materielNum, HttpServletResponse response) {
		
		logger.info("创建拆箱计划时，在良品库查询 库存信息查询条件为：，"+JSONArray.fromObject(jyyInfoGood)+"物料号："+materielNum);
		
		if(null != materielNum && !"".equals(materielNum)){
			String [] split = materielNum.split(",");
			for(int i = 0; i < split.length; i ++){
				if(i == 0) {
					jyyInfoGood.setMaterielNum1(split[0]);
				}else if(i == 1) {
					jyyInfoGood.setMaterielNum2(split[1]);
				}else if(i == 2) {
					jyyInfoGood.setMaterielNum3(split[2]);
				}else if(i == 3) {
					jyyInfoGood.setMaterielNum4(split[3]);
				}else if(i == 4) {
					jyyInfoGood.setMaterielNum5(split[4]);
				}
			}
		}
		
		//带条件的分页查询 良品库存
		List<JyyInfoGood> list = UnpackingService.selectPageGood(jyyInfoGood);
		//统计 良品库库存 总记录数
		//int total = UnpackingService.selectCountGood(jyyInfoGood);
		
		JsonConfig jsonConfig = new JsonConfig();
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", list.size());
		try {
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			logger.info("创建拆箱计划时，在良品库查询 库存信息查询出错");
			e.printStackTrace();
		}
	}
	//------------------------------------------------------------------------------------------------------------------
	
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/toJyyUnpacking")
	public String pageUnpacking (Model model) {
		List<Customer> customer_type0 = stockOutOrderService.queryAllCustomerByType();
		model.addAttribute("customer_type0", customer_type0);
		return "/jyy/jyyUnpacking";
	}
	
	/** 
	 * 根据主键id查询实体（用不到）
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public JyyUnpacking queryById(Long id) {
		JyyUnpacking param = UnpackingService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<JyyUnpacking> queryAllByMution(JyyUnpacking param) {
		List<JyyUnpacking> list = UnpackingService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/list")
	public void list(JyyUnpacking param,HttpServletResponse response, HttpSession httpSession) {
		
		logger.info("拆箱计划带条件的分页查询，条件为：，"+JSONArray.fromObject(param));
		
		//--------------------------------jyy2019-11-07新增start-----------------------------------
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		//--------------------------------jyy2019-11-07新增end-----------------------------------
		param.setType("0");
		//条件分页查询内容
		List<JyyUnpacking> list = UnpackingService.findPageByMution(param);
		//条件查询总条数
		Integer total = UnpackingService.selectCountByMution(param);
		//转为json数据传至页面
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", total);
		try {
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			logger.info("拆箱计划带条件的分页查询出错");
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/insert")
	public void insert(JyyUnpacking param, HttpServletResponse response, HttpSession httpSession) {
		try {
			logger.info("拆箱单据--新增功能--前台参数为：，"+param.toString());
			//获取当前操作人
			ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
			Long uid = su.getId();
			//--------------------------------jyy2019-11-01新增start-----------------------------------
			Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
			param.setWarehouse_id(warehouse_id);
			//--------------------------------jyy2019-11-01新增end-----------------------------------
			param.setCreateDate(DateUtil.dateFormat3());
			param.setCreateName(uid);
			param.setState(0);
			param.setType("0");
			logger.info("拆箱单据--新增功能--处理后参数为：，"+param.toString());
			Long id = UnpackingService.insert(param);
			
			response.getWriter().print(id);
		} catch (IOException e) {
			logger.error("拆箱单据--新增功能--出错--前台参数为："+param.toString());
			e.printStackTrace();
		}
	}
	
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	*/
	@RequestMapping("/update")
	public void update(JyyUnpacking param,HttpServletResponse response){
		Integer count = UnpackingService.update(param);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		String ids2 = "";
		
		String[] splits = ids.split(","); 
		for (String s : splits) {
			Long id = Long.valueOf(s);
			JyyUnpacking param1 = new JyyUnpacking();
			param1.setId(id);
			List<JyyUnpacking> list = UnpackingService.queryAllByMution(param1);
			if(list.size() > 0) {
				//根据计划单号查询详情
				UnpackDetal param = new UnpackDetal();
				param.setOrdernum(list.get(0).getOrdernum());
				List<UnpackDetal> list2 = UnpackDetalService.queryAllByMution(param);
				
				if(list2.size() > 0) {
					for(int i = 0; i < list2.size(); i++) {
						if(i == 0) {
							ids2 = list2.get(i).getId()+"";
						}else {
							ids2 = ","+list2.get(i).getId();
						}
						 
					}
				}
			
			}
			//删除明细
			UnpackDetalService.delete(ids2);
		}
		//删除单子
		Integer count = UnpackingService.delete(ids);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@Autowired
	private IDicMapper iDicMapper;

	/**
	 * 看板拆箱计划展示
	 */
	@RequestMapping("kanBanPlanUnpacking")
	public void kanBanPlanUnpacking(JyyUnpacking param1,UnpackDetal param2,HttpServletResponse response) throws Exception {

		List<UnpackDetal> kanBanList = new ArrayList<>();

		//param1.setType("0");
		//条件分页查询内容
		List<JyyUnpacking> list = UnpackingService.findPageByMution(param1);
		//已经拆箱确认的
		if (list.size() > 0) {
			for (JyyUnpacking pk : list) {
				if (pk.getState() == 0) {
					param2.setOrdernum(pk.getOrdernum());
					List<UnpackDetal> detalList = UnpackDetalService.findPageByMution(param2);
					for (UnpackDetal unpackDetal : detalList) {
						String customerName = iDicMapper.getCustomerBymaId(unpackDetal.getMid());
                        //List<Customer> customerList = customerService.queryCustomerCriteriaByType(criteria);
						//紧急程度
						unpackDetal.setWorklog(pk.getRemark());
						//客户名
						unpackDetal.setType(customerName);
					}
					kanBanList.addAll(detalList);
				}
			}

		}


		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(kanBanList, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", 10);
		ResponseUtil.write(response, result);

	}
	
}
